//
//  WBTitleButton.swift
//  新浪微博
//
//  Created by 名品导购网MPLife.com on 2017/11/29.
//  Copyright © 2017年 sweet. All rights reserved.
//

import UIKit

class WBTitleButton: UIButton {
    //如果title为nil 就显示首页
    //如果title为nil 显示title和箭头
    init(title:String?) {
        super .init(frame: CGRect())
        //判断title是否为nil
        if title == nil {
            setTitle("首页", for: .normal)
        }else{
            setTitle(title, for: .normal)
            //设置图像
            setImage(UIImage(named: "navigationbar_arrow_down"), for: .normal)
            setImage(UIImage(named: "navigationbar_arrow_up"), for: .selected)
        }
        //设置字体和颜色
        
        self .titleLabel?.font = UIFont .boldSystemFont(ofSize: 17)
        setTitleColor(UIColor .darkGray, for: .normal)
        //设置大小
        sizeToFit()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("错误")
    }
    //重新布局子视图
    override func layoutSubviews() {
        //一定要supper重新调用一下父视图
        super .layoutSubviews()
        //判断lable和imageview是否同时存在
        guard let titleLabel = titleLabel, let imageView = imageView else {
            return
        }
        //将label的x向左移动imageView的宽度 将imageView的x向右移动label的宽度
        titleLabel.frame = titleLabel.frame.offsetBy(dx: -imageView.bounds.width, dy: 0)
        titleLabel.frame.origin.x = 0

        imageView.frame = CGRect(x: titleLabel.frame.origin.x + titleLabel.frame.size.width, y: imageView.frame.origin.y, width: imageView.frame.size.width, height: imageView.frame.size.height)
    }
}
